import Mock from 'mockjs';

// 模拟成功的用户信息响应
Mock.mock('/api/user', 'get', {
  code: 0,
  data: {
    id: '@id',
    name: '@cname',
    email: '@email'
  },
  message: '获取用户信息成功'
});

// 模拟失败的响应
Mock.mock('/api/unauthorized', 'get', () => {
  return {
    code: 401,
    data: null,
    message: '未授权访问'
  };
});

// 拦截 uni.request
const originalRequest = uni.request;

// @ts-ignore - Mock 内部属性类型问题
const mockData = (Mock as any)._mocked;

uni.request = ((options: UniApp.RequestOptions) => {
  const { url, success, fail } = options;
  
  try {
    // 查找匹配的 mock 数据
    const mockItem = mockData?.[url];
    if (mockItem) {
      const response = Mock.mock(mockItem.template);
      // 模拟异步响应
      setTimeout(() => {
        if (response.code === 0) {
          success?.({
            statusCode: 200,
            data: response,
            header: {},
            cookies: []
          });
        } else {
          fail?.({
            errMsg: response.message
          });
        }
      }, 300);
      
      // 返回一个符合 RequestTask 接口的对象
      return {
        abort() {},
        onHeadersReceived() {},
        offHeadersReceived() {}
      } as UniApp.RequestTask;
    }
    
    // 如果没有匹配的 mock 数据，使用原始请求
    return originalRequest(options);
  } catch (error) {
    fail?.({
      errMsg: '请求失败'
    });
    // 返回一个符合 RequestTask 接口的对象
    return {
      abort() {},
      onHeadersReceived() {},
      offHeadersReceived() {}
    } as UniApp.RequestTask;
  }
}) as typeof uni.request 